from flask import render_template, flash, redirect, url_for, Blueprint
from sqlalchemy import select, update

from flaskLogin.forms import LoginForm
from flask_login import login_user, logout_user, login_required, current_user
from flaskLogin.models import Account, Account_logging
from flaskLogin.extensions import db
from flaskLogin.utils import redirect_back
import uuid
from datetime import datetime

from flaskLogin import test_transaction

sign_bp = Blueprint('sign', __name__)


@sign_bp.route('/index')
@login_required
def index():
    return render_template('index.html')


@sign_bp.route('/login', methods=['GET', 'POST'])
def login():
    # test_transaction.note_insert()
    if current_user.is_authenticated:
        return redirect(url_for('sign.index'))

    form = LoginForm()
    if form.validate_on_submit():
        userid = form.userid.data
        password = form.password.data
        # remember = form.remember.data
        user = db.session.execute(select(Account).filter_by(userid=userid)).scalar_one_or_none()
        if user:
            if userid == user.userid and user.validate_password(password):
                log = Account_logging()
                log.c_date = datetime.now()
                log.alternative_id = uuid.uuid1()  # 每次登录，重置alternative_id
                log.account_id = user.id
                db.session.add(log)  # 新增account_logging表
                db.session.execute(  # 更新account表
                    update(Account).where(Account.id == user.id).values(last_login=log.c_date,
                                                                        alternative_id=log.alternative_id))
                db.session.commit()
                login_user(user=user, remember=True)  # remeber似乎有bug，哪怕设为False也会执行user_loader
                return redirect_back()
            else:
                flash('账号或密码错误.', 'warning')
        else:
            flash('该账号不存在.', 'danger')
        return redirect(url_for('sign.login'))

    return render_template('login.html', form=form)


@sign_bp.route('/logout')
@login_required
def logout():
    logout_user()
    flash('已登出.', 'info')
    return redirect(url_for('sign.login'))


@sign_bp.route('/')
def helloworld():
    return redirect(url_for('sign.login'))


'''
    1.insert 实例化模型 db.session.add(xx)
    2.select 用：db.session.execute(select(Xx))
    3.update 用：db.session.execute(update(Xx))
    4.delete 用：db.session.execute(delete(Xx))
'''
